/**
 * Copyright 2015 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2015年8月28日 下午3:19:51
 */
package com.absir.appserv.system.service;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.Session;

import com.absir.appserv.system.bean.JPayHistory;
import com.absir.appserv.system.bean.JPayTrade;
import com.absir.appserv.system.dao.BeanDao;
import com.absir.appserv.system.dao.utils.QueryDaoUtils;
import com.absir.bean.basis.Base;
import com.absir.bean.core.BeanFactoryUtils;
import com.absir.bean.inject.value.Bean;
import com.absir.core.util.UtilAbsir;
import com.absir.orm.transaction.value.Transaction;

/**
 * @author absir
 *
 */
@Base
@Bean
public class OpenService {

	/** ME */
	public static final OpenService ME = BeanFactoryUtils.get(OpenService.class);

	/** tokenMap */
	private Map<String, Object> tokenMap = new HashMap<String, Object>();

	/**
	 * @param payTrade
	 * @param tradeNo
	 */
	@Transaction
	public boolean addPayHistory(JPayTrade payTrade, String tradeNo) {
		Object token = UtilAbsir.getToken(tradeNo, tokenMap);
		synchronized (token) {
			try {
				String platform = payTrade.getPlatform();
				Session session = BeanDao.getSession();
				if (QueryDaoUtils
						.createQueryArray(session, "SELECT o FROM JPayHistory o WHERE o.platform = ? and o.tradeNo = ?", platform,
								tradeNo).iterate().hasNext()) {
					return false;
				}

				JPayHistory payHistory = new JPayHistory();
				payHistory.setId(payTrade.getId());
				payHistory.setPlatform(platform);
				payHistory.setTradeNo(tradeNo);
				session.persist(payHistory);
				return true;

			} finally {
				UtilAbsir.clearToken(tradeNo, tokenMap);
			}
		}
	}

}
